package controllers

import (
	"github.com/kataras/iris/v12"
	"github.com/spf13/viper"
	"storeManageApi/models/authModels"
	"storeManageApi/models/requestModels"
	"storeManageApi/models/responseModels"
	"storeManageApi/service"
)

type DefaultController struct {
	Ctx      iris.Context
	Response service.IResponse
}

func (request DefaultController) Get() responseModels.Response {
	return request.Response.DEVELOP()
}
func (request DefaultController) GetIsLogin() responseModels.Response {
	var token string = request.Ctx.GetHeader("AuthBasic")
	if token == "" {
		return request.Response.IsLoginErr("token不存在!请先登录！")
	}
	_, err := service.UtilService.ParseToken(token)
	if err != nil {
		return request.Response.IsLoginErr(err.Error())
	}
	return request.Response.OK("身份有效！")
	//return request.Response.DEVELOP()
}
func (request DefaultController) PostLogin() responseModels.Response {
	var form requestModels.LoginForm = requestModels.LoginForm{}
	request.Ctx.ReadJSON(&form)
	err := form.Isvalidated()
	if err != nil {
		return request.Response.IsvalidatedError(err.Error())
	}
	var account string = viper.GetString("config.admin.Account")
	var password string = viper.GetString("config.admin.Password")
	var userName string = viper.GetString("config.admin.Name")
	if form.Account == account && form.Password == password {
		var authUser authModels.UserAuth = authModels.UserAuth{
			UserName: userName,
			Account:  account,
		}
		token, tokenErr := service.UtilService.CreateJWT(authUser)
		if tokenErr != nil {
			return request.Response.IsLoginErr("Token生成失败!")
		}
		return request.Response.OK(token)
	}
	return request.Response.IsLoginErr("账号或密码错误！")
}
